# -*- coding: utf-8 -*-

#    Copyright (C) 2014 by Promotux
#                       di Francesco Meloni snc - http://www.promotux.it/

#    Author: Francesco Meloni  <francesco@promotux.it>

#    This file is part of OdCollect.

#    OdCollect is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    OdCollect is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with OdCollect.  If not, see <http://www.gnu.org/licenses/>.


import base64
import datetime
import hashlib
import ConfigParser
from web_lib.page import Page
from web_lib.webutils import Response, expose,leggiInSessione , permalinkaTitle , salvaInSessione  , json
from lib.utils import *
from Environment import STATIC_PATH , CACHE_DIR , COOKIENAME , SESSION_DIR

if not os.path.exists(SESSION_DIR):
    SESSION_DIR = "/home/promo/odmc/session"

@expose('/italiaCives/getInfoOperatore')
def get_info_operatore_ic(req, subdomain=None):
    """
    Home page
    """
    from dao.Operatore import Operatore
    md55 = req.form.get("md5")
    try:
        sid = req.cookies[COOKIENAME]
    except:
        sid = "ERRORE SID"
    config = ConfigParser.RawConfigParser()
    valore = None
    session_file = SESSION_DIR + "/" + md55
    config.read(session_file)
    if config.has_option("Main", "schema"):
        ente = config.get("Main", "schema")
        #print " ENTEEEEEEEEEEEEEEEEEEEEEEEEEEEE", ente
    if leggiInSessione(sezione="Main", chiave="id_oper"):
        id_oper = leggiInSessione(sezione="Main", chiave="id_oper")
        if id_oper:
            oper = Operatore().getRecord(id=id_oper)
            item = prep2json(oper),
            jasoned = json.dumps(item,sort_keys=True, indent=4, separators=(',', ': '), ensure_ascii=False, encoding='utf8')
        else:
            item = {
                "Result":"ERROR",
                "Message": "nessun operatore"}
            jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        #print " JASONED", jasoned
        return Response(jasoned)
    return Response("ERRORE")



@expose('/italiaCives/registrazione')
def registrazioni_ic(req, subdomain=None):
    """
    Home page
    """
    if not leggiInSessione(sezione="Main", chiave="schema"):
        url_red = "/italiaCives"
    else:
        from dao.Operatore import Operatore
        d = Operatore()
        d.email = str(req.form.get("email"))
        d.cognome = str(req.form.get("cognome"))
        d.nome = str(req.form.get("nome"))
        d.privacy = bool(req.form.get("privacy"))
        d.tipo_operatore = "Cittadino"
        #d.active = bool(req.form.get("active"))
        d.cellulare = str(req.form.get("cellulare"))
        d.last_modified = datetime.datetime.now()
        d.registration_date = datetime.datetime.now()
        d.username = str(req.form.get("email").strip().lower())
        d.password = hashlib.md5(str(req.form.get("email").strip().lower()) + \
                        str(req.form.get("password").strip())).hexdigest()
        stringa= "Cognome: " + str(d.cognome or "") + "\n" + \
                "Nome: " + str(d.nome or "") + "\n" + \
                "Email: " + str(d.email or "") + "\n"+ \
                "Cellulare: " + str(d.cellulare or "") + "\n" + \
                "Codice: " + str(d.password[0:10])
        data = createbarcode(d.password[0:10])
        if data:
            d.f_ean = base64.b64encode(data)
        dataqrcode = createbarcodeqr(stringa)
        if dataqrcode:
            d.f_qrcode = base64.b64encode(dataqrcode)
        d.persist()
        salvaInSessione(req, sezione="Main", chiave="id_oper", valore=d.id)
        url_red = "/italiaCives/dashboard"
    return Page(req).redirect(url_red)
